package source
{
	import com.justinbuser.core.MobileApplication;
	import com.justinbuser.net.DynamicURLLoader;
	import com.justinbuser.singleton.Core;
	
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.net.navigateToURL;
	
	import spark.components.ViewMenuItem;
	
	import views.Login;
	import views.Reports;
	
	[Bindable] public class MainApplication extends MobileApplication
	{
		public static var mainViewMenuItems:Vector.<ViewMenuItem>;
		
		public function MainApplication()
		{
			super();
			trace('MainApplication');
		}
		
		override public function init():void{
			trace('init called');
			core = new Core(null,Vector.<Class>([BattleReport,FullBattleReport,BattleAward,BattlePersona]));
			firstView = core.authenticated ? views.Reports : views.Login;
			if(!core.pollingInterval) 
			{
				core.pollingInterval = 60;
				core.remember = true;
				core.autoUpdate = true;
				core.reportCache = {};
			}
			loadTranslations();
		}
		
		public function loadTranslations():void{
			trace('loading translations');
			var loader:DynamicURLLoader = new DynamicURLLoader(parseResponse);
			loader.open("http://battlelog-cdn.battlefield.com/public/generated/en_US/surfacetranslations.js",null,10,"GET");
			
			function parseResponse(e:Event):void{
				trace('loaded translations');
				var response:String = String(e.target.data);
				response = response.substr(response.indexOf("{"));
				response = response.substr(0,-1);
				core.translations = JSON.parse(response);
			}
		}
		
		public function logout():void{
			trace('logging out');
			var loader:DynamicURLLoader = new DynamicURLLoader(showLoginView);
			loader.open('http://battlelog.battlefield.com/bf3/session/logout/',null,2,"GET");
			
			function showLoginView(e:Event):void{
				core.authenticated = false;
				navigator.popAll(null);
				navigator.pushView(views.Login);
			}
			
		}
		
		public function loadBattlelog(e:Event):void{
			var request:URLRequest = new URLRequest("http://battlelog.battlefield.com/bf3/gate/login/");
			var varz:URLVariables = new URLVariables();
			varz.email = String(core.email);
			varz.submit = "Sign in";
			varz.remember = 1;
			varz.password = String(core.password);
			varz.redirect = "";
			request.data = varz;
			request.method = "POST";
			navigateToURL(request);
		}
		
		public function showSettings():void{
			if(navigator.activeView is Login){ 
				trace('Login');	
			}
			else{
				trace('not Login');
				//navigator.popAll(null);
				navigator.pushView(views.Login,{skipLogin:true});
			}
		}
		
		/*public function checkAuthStatus():void{
			//actionBar.titleGroup.setStyle('color',0xFF6600);
			if(!core.remember || !core.password || !core.authenticated){
				navigator.pushView(views.Login);
			}
		}*/
	}
}